<?php

require_once __DIR__ . '/vendor/autoload.php';

function process($imagePath)
{
    $imagick = new Imagick($imagePath);
    $imagick->scaleImage(28, 28);


    $pixels = [];
    $pixelsIterator = $imagick->getPixelIterator();
    foreach ($pixelsIterator as $row => $pixelList) {
        foreach ($pixelList as $col => $pixel) {
            $blueValue = $pixel->getColorValue(Imagick::COLOR_BLUE);
            $greenValue = $pixel->getColorValue(Imagick::COLOR_GREEN);
            $redValue = $pixel->getColorValue(Imagick::COLOR_RED);
            $pixelVal = $blueValue + $greenValue + $redValue;
            if ($pixelVal < 3) {
                $pixels[] = $blueValue + $greenValue + $redValue;
            }
        }
    }

    $avgPixel = array_sum($pixels) / count($pixels);
    $filteredPixels = [];

    $pixelsIterator = $imagick->getPixelIterator();
    foreach ($pixelsIterator as $row => $pixelList) {
        foreach ($pixelList as $col => $pixel) {
            $blueValue = $pixel->getColorValue(Imagick::COLOR_BLUE);
            $greenValue = $pixel->getColorValue(Imagick::COLOR_GREEN);
            $redValue = $pixel->getColorValue(Imagick::COLOR_RED);
            $pixelVal = $blueValue + $greenValue + $redValue;
            if ($pixelVal < 3) {
                if ($pixelVal >= $avgPixel) {
                    $pixel->setColorValue(Imagick::COLOR_BLUE, 1);
                    $pixel->setColorValue(Imagick::COLOR_GREEN, 1);
                    $pixel->setColorValue(Imagick::COLOR_RED, 1);
                    $pixelVal = 3;
                }
            }
            $filteredPixels[] = $pixelVal;
        }
        $pixelsIterator->syncIterator();
    }

    return $filteredPixels;
}

$imagePath = $argv[1];

$flag = isset($argv[2]) ? $argv[2] : 2;
if ($flag == 1) {
    $type = 'print';
} else {
    $type = 'valve';
}

$model = (new \Phpml\ModelManager())->restoreFromFile(__DIR__ . '/model/' . $type . '.model');
var_dump($model->predict(process($imagePath)));
